/**
 * @fileoverview Creates a story (i.e., chart + text). The text is customized
 * for each of the condition by modifying placeholders in the original template
 * with values specified in the story data object.
 */

/**
 * Total number of conditions in the study.
 */
var CONDITION_NUM = 4;

/**
 * Condition types in the study.
 */
var Conditions = {
  INT_NONE: 0,
  INT_TEXT: 1,
  INT_GRAPHIC: 2,
  INT_INTERACTIVE: 3
}

/**
 * Placeholder and values for each test condition in text.data field in
 * the stories variable in data.js.
 */
var ConditionValues = {
  0: {},
  1: {'{1}': 'The bar chart on the right shows: '},
  2: {},
  3: {'{3s}': '<span onmouseover="setSelection(this);' +
               'this.className=\'select\'"; " ' +
               'onmouseout="clearSelection(this);' +
               'this.className=\'hover\'"; ' +
               'class="hover">',
      '{3e}': '</span>'}
}

/**
 * Placesholders in the story text template.
 */
var StoryPlaceHolders = ['{1}', '{3s}', '{3e}'];

/**
 * Creates the front-page version of a story, which includes:
 * - headline
 * - image
 * - teaser text
 * @param {number} index Story index in the stories variable in data.js.
 * @return {Element} the container with the story.
 */
function createFrontPageStory(stage, index) {
  var story = stories[index];
  var container = document.createElement('div');
  stage.appendChild(container);

  var containerClassName = (index % 2 == 0) ? 'even' : 'odd';
  container.className = 'fp-container-' + containerClassName;

  var headlineDiv = document.createElement('div');
  headlineDiv.innerHTML = '<div class="fp-headline selectable" ' +
      'onclick="createStoryPage(' + index + ')">' + story.headline +
      '</div>';
  var headline = headlineDiv.removeChild(headlineDiv.firstChild);
  container.appendChild(headline);

  var tableDiv = document.createElement('div');
  tableDiv.innerHTML = '<table><tr><td>' +
     '<img id="'+ index + '" class="fp-image selectable" src="' +
          story.imageSrc + '" onclick="createStoryPage(' + index + ')" />' +
     '</td><td>' +
     '<div id="' + index + '" class="fp-teaser selectable" ' +
         'onclick="createStoryPage(' + index + ')">' +
         story.teaserText + '<div/>' +
     '</td></tr></table>';
  var table = tableDiv.removeChild(tableDiv.firstChild);

  table.className = 'fp-body';
  container.appendChild(table);

  return container;
}

/**
 * Creates a single story, which consists of a headline, a chart, and a text.
 * @return {Element} the container with the story.
 */
function createStory(opt_lastSelectedRow) {
  var story = stories[storyIndex];
  var condition = ConditionValues[conditionIndex];
  var isGraphicCond = conditionIndex == Conditions.INT_GRAPHIC;
  var dataText = createStoryDataText(story.text.data, condition);

  var container = document.createElement('div');
  container.className = 's-container';

  var headline = document.createElement('div');
  headline.className = 's-headline';
  headline.innerHTML = story.headline;
  container.appendChild(headline);

  var tableDiv = document.createElement('div');
  tableDiv.innerHTML = '<table><tr><td></td><td></td></tr>' +
      '<tr><td></td><td></td></tr></table>';
  var table = tableDiv.removeChild(tableDiv.firstChild);

  //var body = document.createElement('table');
  table.className = 's-body';
  container.appendChild(table);

  // Top row is for context text.
  var contextRow = table.rows[0];
  contextRow.cells[0].colSpan = '2';
  contextRow.cells[0].className = 's-text s-text-context';
  contextRow.cells[0].innerHTML = story.text.context;

  // Second row is for the data and chart.
  // For the "INT-GRAPHIC" version, the text is overlaid on top of the chart.
  if (!isGraphicCond) {
    var textElement = document.createElement('div');
    textElement.className = 's-text s-text-data';
    textElement.innerHTML = dataText;
    table.rows[1].cells[0].appendChild(textElement);
  } else {
    table.rows[1].cells[0].style.width = '25%';
  }
  table.rows[1].cells[1].appendChild(
      createChart(isGraphicCond, opt_lastSelectedRow));

  // -- I have added the button dynamically so that appears in the container
  var buttonDiv = document.createElement('div');
  buttonDiv.innerHTML = '<input type="button" id="s-button" class="button"' +
      'onmouseover="onStoryButtonMouseOver()" ' +
      'onmouseout="onStoryButtonMouseOut()" />';
  var button = buttonDiv.removeChild(buttonDiv.firstChild);
  container.appendChild(button);

  return container;
}

/**
 * Creates the data part of the story text.
 * @param {string} template With placeholders.
 * @param {object} condition Keys are placeholders and values are the value to
 *   be placed. All other placeholders are removed.
 * @return {string} story text.
 */
function createStoryDataText(template, condition) {
  var result = template;
  for (var key in condition) {
    result = globalReplace(result, key, condition[key]);
  }
  return clearStoryPlaceholders(result);
}

/**
 * Removes all placeholders.
 * @param {string} template Text with placeholders.
 * @return {string} cleaned text.
 */
function clearStoryPlaceholders(template) {
  var result = template
  for (var i = 0; i < StoryPlaceHolders.length; i++) {
    result = globalReplace(result, StoryPlaceHolders[i], '');
  }
  return result;
}

/**
 * Replaces all instances of oldValue with newValue.
 * @param {string} text Input text.
 * @param {string} oldValue
 * @parma {string} newValue
 * @return {string} new text
 */
function globalReplace(text, oldValue, newValue) {
  return text.split(oldValue).join(newValue);
}

/**
 * Changes cursor.
 */
function onStoryButtonMouseOver(evt) {
  evt = evt || window.event;
  if (evt && evt.target) {
    evt.target.style.cursor = 'pointer';
  }
}

/**
 * Changes cursor.
 */
function onStoryButtonMouseOut(evt) {
  evt = evt || window.event;
  if (evt && evt.target) {
    evt.target.style.cursor = 'default';
  }
}
